from base64 import b64decode
from pickle import loads

from django_redis import get_redis_connection


def merge_cookies_to_redis(request, user, response):
    """将cookies中的商品信息合并到redis中，以cookies中的信息为准"""
    # 读取cookies中的carts信息
    cookies_str = request.COOKIES.get('carts')
    if cookies_str is None:
        return response
    else:
        # 不为空，进行解码， carts:{'sku_id':{'count': 10, 'selected': True}}
        carts = loads(b64decode(cookies_str))

    # 初始化数据
    carts_hash = {}  # 存放购物车中的商品的ID和数量
    selected_id_list = []  # 存放已选中商品的ID
    unselected_id_list = []  # 存放未选中商品的ID

    # 取出每一个商品id和数量、选中状态的字典
    for sku_id, count_selected_dict in carts.items():
        carts_hash[sku_id] = count_selected_dict['count']
        if count_selected_dict['selected']:
            selected_id_list.append(sku_id)
        else:
            unselected_id_list.append(sku_id)

    # 连接redis，更新数据
    conn = get_redis_connection('carts')
    pipe = conn.pipeline()
    pipe.hmset('carts_%s' % user.id, carts_hash)
    if len(selected_id_list) > 0:
        pipe.sadd('selected_%s' % user.id,
                  *selected_id_list)  # 对selected_id_list进行拆包
    if len(unselected_id_list) > 0:
        pipe.srem('selected_%s' % user.id,
                  *unselected_id_list)  # 对unselected_id_list进行拆包
    pipe.execute()

    response.delete_cookie('carts')
    return response
